﻿using System;
using System.Windows;
using Box2DX.Collision;
using Box2DX.Dynamics;

using System.Windows.Interactivity;

namespace Expression.Samples.Physics.Behaviors
{
	
	
	public class BodyBehavior : PhysicsBehavior<FrameworkElement>
	{
		private Entity entity;
		private BodyParameters bodyParameters;

		public BodyBehavior() {
			this.bodyParameters = new BodyParameters();
		}

		private Body Body {
			get {
				return this.entity.Body; 
			}
		}

		public Entity Entity {
			get { return this.entity; }
		}

		public bool IsStatic  { 
			get { return this.BodyParameters.IsStatic; } 
			set { this.BodyParameters.IsStatic = value; } 
		}

		public double Density {
			get { return this.BodyParameters.Density; }
			set { this.BodyParameters.Density = value; }
		}
		
		public double Friction {
			get { return this.BodyParameters.Friction; }
			set { this.BodyParameters.Friction = value; }
		}

		public double Restitution {
			get { return this.BodyParameters.Restitution; }
			set { this.BodyParameters.Restitution = value; }
		}

		public Vector InitialVelocity {
			get { return this.BodyParameters.InitialVelocity; }
			set { this.BodyParameters.InitialVelocity = value; }
		}

		public double InitialRotationalVelocity {
			get { return this.BodyParameters.InitialRotationalVelocity; }
			set { this.BodyParameters.InitialRotationalVelocity = value; }
		}

		public bool CanRotate {
			get { return this.BodyParameters.CanRotate; }
			set { this.BodyParameters.CanRotate = value; }
		}

		public double LinearDamping {
			get { return this.BodyParameters.LinearDamping; }
			set { this.BodyParameters.LinearDamping = value; }
		}

		public double AngularDamping {
			get { return this.BodyParameters.AngularDamping; }
			set { this.BodyParameters.AngularDamping = value; }
		}

		private BodyParameters BodyParameters
		{
			get { return this.bodyParameters; }
		}

		protected override void  OnAttached()
		{
 			base.OnAttached();

			this.entity = new Entity(this.AssociatedObject);

			this.AssociatedObject.Loaded += this.newElement_Loaded;
		}


		private void newElement_Loaded(object sender, RoutedEventArgs e)
		{
			this.AssociatedObject.Loaded -= this.newElement_Loaded;

			Simulator simulator = this.Simulator;

			if (simulator == null) {
				this.Dispatcher.BeginInvoke(delegate {
					this.Simulator.AddEntity(this.entity, this.BodyParameters);

					this.entity.Body.AllowSleeping = true;
				});
			}
			else {
				simulator.AddEntity(this.entity, this.BodyParameters);
				this.entity.Body.AllowSleeping = true;;
			}
		}


		

		

	
		
	}
}